#!/usr/bin/python3


from log import *

import cx_Oracle

class COracleDB21CXE:
    def __init__(self, log, dbHost="10.1.53.247", dbPort=1521,
                 dbUser="c##shengli", dbPwd="shengli0",
                 dbName="xe"):
        self.log = log
        self.dbHost = dbHost
        self.dbPort = dbPort
        self.dbUser = dbUser
        self.dbUserPwd = dbPwd
        self.dbName = dbName

    def init(self):
        try:
            self.DB = cx_Oracle.connect(self.dbUser + "/" +self.dbUserPwd +
                                        "@//" + self.dbHost+":"+str(self.dbPort)+"/" + self.dbName)
            self.cursor = self.DB.cursor()
            self.log.log("connect to oracle database :" + self.dbHost + ":" + str(self.dbPort) + ":" +self.dbName)
        except cx_Oracle.Error as e:
            self.log.log("connect to oracle database fialed:" + self.dbHost + ":" + str(self.dbPort), error)
            return e

    def close(self):
        try:
            self.cursor.close()
            self.DB.close()
        except:
            return

    def query(self, queryStr):
        try:
            self.log.log("oracle query, sql:" + queryStr)
            self.cursor.execute(queryStr)
        except cx_Oracle.DatabaseError as e:
            self.log.log("oracle query failed, error:" + queryStr + str(e))
            return e

    def exec(self, execStr, tableName):
        try:
            self.DB.cursor.execute("lock table " + tableName + " in row share mode wait 10;")
            self.log.log("oracle exec, sql:" + execStr)
            self.cursor.execute(execStr)
            self.DB.commit()

        except cx_Oracle.DatabaseError as e:
            self.DB.rollback()
            self.log.log("oracle exec failed, rollback, sql:" + execStr + " error:" + str(e), error)
            return e


    def getData(self):
        try:
            rows = self.cursor.fetchall()
            return rows
        except cx_Oracle.Error as e:
            self.log.log("oracle get data failed, error:" + str(e))

            return e







#已测试
testLog = CLog(logName="test.log", isPrint=True)

testDB = COracleDB21CXE(log=testLog, dbHost="10.1.53.247", dbUser="c##shengli", dbPwd="shengli0", dbName="xe")
testDB.init()

testDB.query(queryStr="select * from ATDC_ATTENDANCE_DETAIL")
data = testDB.getData()
print(data)




